<template>
  <el-form label-width="100px" ref="skuFormRef" :model="skuInfo" :rules="rules">
    <!-- form中绑定数据,使用:model -->
    <el-form-item label="SPU名称">
      <span>{{ props.getSkuInfo.spuName }}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
      <el-input-number class="mx-4" v-model="skuInfo.price" style="width: 100%" :min="1" :max="10" controls-position="right" />
    </el-form-item>
    <el-form-item label="重量(千克)" prop="weight">
      <el-input-number style="width: 100%" v-model="skuInfo.weight" class="mx-4" :min="1" :max="10" controls-position="right" />
    </el-form-item>
    <el-form-item label="规格描述" prop="skuDesc">
      <el-input type="textarea" rows="4" v-model="skuInfo.skuDesc" />
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="20">
        <el-col v-for="(attr, index) in attrList" :key="attr.id" :md="12" :sm="12" :xs="24" :lg="8">
          <el-form-item :label="attr.attrName">
            <el-select v-model="skuInfo.skuAttrValueList[index]" @change="clearAttrRules">
              <el-option v-for="attrValue in attr.attrValueList" :key="attrValue.id" :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`" :label="attrValue.valueName" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-row :gutter="20">
        <el-col v-for="(saleAttr, index) in spuSaleAttrList" :key="saleAttr.id" :md="24" :sm="24" :xs="24" :lg="8">
          <el-form-item :label="saleAttr.saleAttrName">
            <el-select v-model="skuInfo.skuSaleAttrValueList[index]" @change="clearSaleAttrRules">
              <el-option
                v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                :label="saleAttrValue.saleAttrValueName"
                :key="saleAttrValue.id"
              />
              <!-- 在表单绑定的数据中,使用v-model绑定对应的option值还得使用value不然提示警告,一定要有value,这个值也是绑定到对应的reactive对象中
              在下拉框这种情况进项数据绑定,需要使用index,才可以在页面呈现对应的选项 
              然后由于请求参数需要option的属性值和id,和对应的select的值和id,在别的地方不能拿到当前选中的,所以我们在value中拿到,并绑定到对应的reactive中,在发请求之前在进行切割,转换成需要的数据格式-->
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <!-- 记住table表格的数据来源是:data -->
      <el-table border :data="spuImageList" style="margin-bottom: 20px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="100"></el-table-column>
        <el-table-column label="图片" width="300">
          <template v-slot="{ row, $index }">
            <el-image :src="row.imgUrl" :alt="row.imgName" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row, $index }">
            <el-button v-if="row.isDefault == 1" type="success" :disabled="isDefault">默认</el-button>
            <el-button v-else type="primary" @click="setDefault(row)">设置默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(skuFormRef)">保存</el-button>
      <el-button type="default" @click="toSpuList">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: "SkuForm",
}
</script>
<script lang="ts" setup>
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from "@/api/product/spu"
import { reqGetAttrListDataByCategory3Id } from "@/api/product/attr"
import { reqSaveSkuInfo } from "@/api/product/sku"
import { ref, onMounted, reactive } from "vue"

import { useCategoryListStore } from "@/stores/categoryList"
import type { FormInstance, FormRules } from "element-plus"
import { ElMessage } from "element-plus"
// 定义变量们来储存响应回来的数据,并响应式的渲染到页面上
// 图片列表
const spuImageList = ref([])
// spu基础属性列表
const spuSaleAttrList = ref([])
// 平台属性列表
const attrList = ref([])
const isDefault = ref("")
// 准备添加SkuInfo时的参数数据
const skuInfo = reactive({
  // spu名称
  skuName: "",
  // 价格
  price: 0,
  // 重量
  weight: 0,
  // 描述
  skuDesc: "",
  // 默认图片
  skuDefaultImg: "",
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性列表
  skuSaleAttrValueList: [],
})

const categoryStore = useCategoryListStore()
// 接受自定义的事件
const emits = defineEmits(["sendShowSpu", "SpuInfo"])
// 接受父组件传递的参数
const props = defineProps(["getSkuInfo"])
// 触发自定义事件,用来跳转组件spuList
const toSpuList = () => {
  emits("sendShowSpu", 1)
}
// 自定义校验规则
const skuFormRef = ref<FormInstance>()

// 书写一个图片的自定义校验规则
const skuImageListValidate = (rule: any, value: any, callback: any) => {
  // console.log("rule", rule, value, callback)
  if (value.length === 0) {
    callback("请至少选择一张图片...")
    return
  }
  if (!value.find(item => item.isDefault === "1")) {
    // 如果找不到默认图片
    callback("请选择默认图片...")
    return
  }
  callback() // 什么参数都不写，表示放行
}
const skuAttrValueListValidate = (rule: any, value: any, callback: any) => {
  // console.log(rule,value)
  if (!value.length) {
    return callback("请选择一个平台属性")
  }
  callback()
}
const skuSaleAttrValueListValidate = (rule: any, value: any, callback: any) => {
  // console.log(rule,value)
  if (!value.length) {
    return callback("请选择一个平台属性")
  }
  callback()
}

const rules = reactive<FormRules>({
  // validator验证控件,写了required才能出现星号*
  skuName: [
    { required: true, message: "请输入Sku名称", trigger: "blur" },
    { min: 1, max: 10, message: "Sku名称在1---10之间", trigger: "blur" },
  ],
  price: [{ required: true, message: "请输入Sku价格", trigger: "change" }],
  weight: [{ required: true, message: "请输入Sku重量", trigger: "change" }],
  skuDesc: [{ required: true, message: "请输入Sku描述", trigger: "blur" }],
  skuImageList: [{ required: true, validator: skuImageListValidate, type: "array", trigger: "change" }],
  skuAttrValueList: [{ required: true, validator: skuAttrValueListValidate, trigger: "change" }],
  skuSaleAttrValueList: [{ required: true, validator: skuSaleAttrValueListValidate, trigger: "change" }],
})

// 页面一挂载完成就需要获取数据,用来渲染页面
onMounted(async () => {
  // 根据传递过来的参数获取id，发送请求
  const id = props.getSkuInfo.id
  // console.log(id)
  // console.log(categoryStore)

  // Promise.allSettled 后面的数组中放入不少以一个的请求,当至少一个成功时,就能成功,与Promise.all不同,.all必须全部成功才行,allsettled允许失败
  // 注意.这里还用到了数组的解构,要注意不同于对象解构的是,数组解构需要顺序一一对应,也就是根据下标或者说是索引,而对象是根据属性来的
  const [resSpuSaleAttrList, resAttrList] = await Promise.allSettled([
    reqGetSpuSaleAttrList(id),
    reqGetAttrListDataByCategory3Id({
      category1Id: categoryStore.category1Id as number,
      category2Id: categoryStore.category2Id as number,
      category3Id: categoryStore.category3Id as number,
    }),
  ])
  // console.log(resSpuSaleAttrList, resAttrList)

  // 赋值:
  spuImageList.value = await reqGetSpuImageList(id)
  if (resSpuSaleAttrList?.status == "fulfilled") {
    spuSaleAttrList.value = resSpuSaleAttrList.value.map(item => {
      return {
        ...item,
        // 追加一个默认属性,便于展示
        isDefault: "",
      }
    })
    // 后面加value是因为响应的数据就是这种格式
  }
  if (resAttrList?.status === "fulfilled") {
    attrList.value = resAttrList.value
  }
})

// 设置默认图片
const setDefault = row => {
  // console.log(23)
  // 但是默认图片只能有一张,设置排他属性
  spuImageList.value.forEach(item => {
    item.isDefault = "0"
  })
  row.isDefault = "1"
  // 保存一下默认图片的地址
  skuInfo.skuDefaultImg = row.imgUrl
}

// 选中图片
const handleSelectionChange = (val: User[]) => {
  console.log(val)
  skuInfo.skuImageList = val
}

// 点击保存发送请求
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 发送请求之前需要将下拉框的数据处理一下
      skuInfo.spuId = props.getSkuInfo.id
      skuInfo.category3Id = props.getSkuInfo.category3Id
      // 平台属性
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList.filter(Boolean).map(item => {
        // 注意,数据格式和名称都要严格按照请求参数来定义
        const [attrId, attrName, valueId, valueName] = item.split(":")
        return {
          attrId,
          attrName,
          valueId,
          valueName,
        }
      })
      // 售卖属性
      skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList.filter(Boolean).map(item => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = item.split(":")
        return {
          saleAttrId,
          saleAttrName,
          saleAttrValueId,
          saleAttrValueName,
        }
      })
      await reqSaveSkuInfo(skuInfo)
      ElMessage.success("添加sku数据成功...")
      emits("sendShowSpu", 1)
    } else {
      console.log("error submit!", fields)
    }
  })
}

//  清空平台属性的校验规则
const clearAttrRules = () => {
  // 注意要清空对应的规则,需要写在clearValidate函数中的数组中
  skuFormRef.value?.clearValidate(["skuAttrValueList"])
}
//  清空销售属性的校验规则
const clearSaleAttrRules = () => {
  console.log("事件触发...aaaa")
  skuFormRef.value?.clearValidate(["skuSaleAttrValueList"])
}
</script>

<style></style>
